<template>
  <view class="page">
    <!-- 下拉刷新 -->
    <scroll-view
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="onLoadMore"
      class="scroll-box"
    >
      <!-- 分段列表 -->
      <view v-for="(section, date) in sectionList" :key="date">
        <!-- 分段标题 -->
        <view class="section-title">{{ date }}</view>

        <!-- 卡片列表 -->
        <view v-for="item in section.list" :key="item.id" class="card">
          <!-- 上 -->
          <view class="shang">
            <!-- 左侧：金额 -->
            <view class="left">
              <text class="amount">¥{{ item.amount }}</text>
            </view>
            <!-- 右侧：时间 -->
            <view class="right">
              <text class="time">{{ item.createTime }}</text>
            </view>
          </view>
          <!-- 下 -->
          <view class="no">订单号：{{ item.orderNo }}</view>
        </view>
      </view>

      <!-- 触底加载 -->
      <view v-if="loading" class="loading">加载中...</view>
      <view v-if="!hasMore && total>0" class="no-more">没有更多了</view>

      <!-- 空状态 -->
      <view v-if="total===0 && !loading" class="empty">
        <text class="empty-txt">暂无提现记录</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { GetTixianList } from '../../../api/tixian'

/* ========== 响应式数据 ========== */
const list        = ref([])        // 提现记录
const loading     = ref(false)     // 触底加载状态
const refreshing  = ref(false)     // 下拉刷新状态
const hasMore     = ref(true)      // 是否还有下一页
const page        = ref(1)         // 当前页码
const total       = ref(0)         // 总条数（接口返回）

/* ========== 分段展示（今天/昨天/更早） ========== */
const sectionList = computed(() => {
  const sections = {}
  list.value.forEach(item => {
    const date = formatSection(item.createTime)
    if (!sections[date]) sections[date] = { list: [] }
    sections[date].list.push(item)
  })
  return sections
})

/* ========== 工具函数 ========== */
// 分段文案
function formatSection(timeStr) {
  const d = new Date(timeStr.replace(/-/g, '/'))
  const today = new Date()
  const ytd = new Date(today - 86400000)
  if (d.toDateString() === today.toDateString()) return '今天'
  if (d.toDateString() === ytd.toDateString()) return '昨天'
  return d.toLocaleDateString()
}

// 生成固定订单号（接口暂无字段）
function mockOrderNo() {
  return 'WD' + Date.now().toString().slice(-8)
}

/* ========== 数据加载 ========== */
async function loadData(isRefresh = false) {
  if (isRefresh) page.value = 1
  loading.value = true

  try {
    // 请求接口
    const res = await GetTixianList({ page: page.value })
    if (res.code !== 0 || !res.data?.order_list) throw new Error(res.msg || '接口异常')

    const { order_list } = res.data

    // 格式化数据
    const formatted = order_list.map((it, idx) => ({
      id: `${page.value}-${idx}`,
      amount: it.amount,
      createTime: it.time,
      orderNo: mockOrderNo() // 固定写法
    }))

    // 更新列表
    if (isRefresh) list.value = []
    list.value.push(...formatted)
    total.value = list.value.length

    // 判断是否还有下一页（根据实际接口分页字段调整）
    hasMore.value = order_list.length === 10 // 假设每页 10 条
  } catch (err) {
    uni.showToast({ title: err.message || '加载失败', icon: 'none' })
    hasMore.value = false
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

/* ========== 事件 ========== */
function onRefresh() {
  refreshing.value = true
  loadData(true)
}

function onLoadMore() {
  if (hasMore.value && !loading.value) {
    page.value += 1
    loadData()
  }
}

/* ========== 生命周期 ========== */
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.page {
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  height: 100vh;
  width: 100%;
  align-items: center;
}

.scroll-box {
  height: 100vh;
  width: 100%;
}

.section-title {
  padding: 20rpx 24rpx;
  font-size: 26rpx;
  color: #909399;
  background: #f5f7fa;
}

.card {
  display: flex;
  width: 95%;
  flex-direction: column;
  align-items: center;
  background: #ffffff;
  border-radius: 10rpx;
  margin: 0 auto 20rpx;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.05);
  padding: 0 20rpx;
}

.shang {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin: 20rpx 0;
}

.left {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.amount {
  font-weight: 520;
  color: #303133;
  font-size: 32rpx;
}

.right {
  text-align: right;
  font-size: 24rpx;
  color: #909399;
}

.no {
  font-size: 22rpx;
  width: 100%;
  color: #909399;
  margin-bottom: 20rpx;
}

.loading,
.no-more {
  text-align: center;
  padding: 40rpx;
  font-size: 26rpx;
  color: #909399;
}

.empty {
  text-align: center;
  padding: 120rpx 0;
}

.empty-txt {
  font-size: 28rpx;
  color: #c0c4cc;
}
</style>